package com.ysmygx.cosumer;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.ysmygx.constants.AuthConstants;
import com.ysmygx.domain.CompanyBalance;
import com.ysmygx.dto.QueryBalanceDTO;
import com.ysmygx.entity.AccountTransHisReq;
import com.ysmygx.entity.AccountTransHisResp;
import com.ysmygx.entity.BalanceResp;
import com.ysmygx.manage.BankManage;
import com.ysmygx.service.ICompanyBalanceService;
import com.ysmygx.utils.BusinessException;
import com.ysmygx.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author laoyanbin
 */
@Slf4j
@Service
@RocketMQMessageListener(topic = "query-balance-topic", consumerGroup = "query_balance_consumer")
public class QueryBalanceConsumer implements RocketMQListener<String> {

    @Resource
    private BankManage bankManage;
    @Resource
    private ICompanyBalanceService companyBalanceService;


    @Override
    public void onMessage(String message) {
        ThreadLocalUtil.set(UUID.fastUUID().toString(true));
        log.info("{},接收到查询账户余额消息：{}",ThreadLocalUtil.get(), message);
        try {
            QueryBalanceDTO dto = JSONUtil.toBean(JSONUtil.parseObj(message).getStr("body"), QueryBalanceDTO.class);
            BalanceResp data = bankManage.getBalance(dto.getAccountNo());

            //更新企业余额到数据库
            CompanyBalance companyBalance = companyBalanceService.selectCompanyBalanceByAccountNo(dto.getAccountNo());
            if (companyBalance == null) {
                companyBalance = new CompanyBalance();
                companyBalance.setBalance(data.getBalance());
                companyBalance.setBalanceAvailable(data.getBalanceAvailable());
                companyBalance.setCompanyName(dto.getCompanyName());
                companyBalance.setBankAccount(dto.getAccountNo());
                companyBalanceService.insertCompanyBalance(companyBalance);
            }else{
                companyBalance.setBalance(data.getBalance());
                companyBalance.setBalanceAvailable(data.getBalanceAvailable());
                companyBalanceService.updateCompanyBalance(companyBalance);
            }

        }catch (Exception e){
            log.error("查询账户余额异常",e);
        }
    }
}






